import {globalConfig} from "../config/globalConfig";
import {GameVar} from "../game/GameVar";
import {SwimShopData} from "../web/model/SwimModel";
import {model} from "../web/model/Model";
import {HeadShopData} from "../web/model/HeadModel";
import {ResType} from "../config/config";
import {COMMON_CID} from "../web/model/UserModel";

function randomName() {
  return globalConfig.name_config[Math.floor(Math.random() * globalConfig.name_config.length)].nickname
}

function btnify(btn: cc.Node, callback?: Function) {
  new BtnSprite(btn, callback);
}

const type1Award: Array<> = globalConfig.award_config.filter(value => (value as any).type === 1);
const type2Award: Array<> = globalConfig.award_config.filter(value => (value as any).type === 2);

function getAward(score: number, rank: number) {
  if (GameVar.mode == 1) {
    const awardItem = type1Award.find(value => (value as any).rank === rank);
    if (awardItem) {
      return awardItem.award;
    }
    return 0;
  } else {
    if (score < type2Award[0].point) {
      return 0
    } else if (score > type2Award[type2Award.length - 1].point) {
      return type2Award[type2Award.length - 1].award;
    }
    for (let i = 0; i < type2Award.length - 1; i++) {
      const next = type2Award[i + 1]
      const curr = type2Award[i]
      if (score >= curr.point && score < next.point) {
        return curr.award;
      }
    }
    return 0;
  }
  // return .award
}

function formatToQuery(params: Object) {
  let array = [];
  for (let key in params) {
    array.push(key + '=' + params[key])
  }
  return array.join('&')
}

function getSwimState(item: SwimShopData) {
  if (model.user.activeSwim === item.id) {
    item.state = 2;
    item.sortScore += 19999;
    return 2;
  }
  //有，未使用
  else if (model.user.getItemNum(item.id) > 0) {
    item.state = 1;
    item.sortScore += 10000;
    return 1;
  }
  //没有，可合成
  else if (item.fragmentId !== 0) {
    //碎片完整，可以合成
    if (model.user.getItemNum(item.fragmentId) >= item.mergeCount) {
      item.state = 3;
      item.sortScore += 100000;
      return 3
    } else if (model.user.getItemNum(item.fragmentId) + model.user.getItemNum(COMMON_CID.PIECE_POWERFUL) >= item.mergeCount) {
      //加上万能碎片可合成
      item.state = 6
      item.sortScore += 100000;
      return 6;
    }
    //碎片缺少
    else {
      item.state = 4;
      return 4;
    }
  }
  else if (item.currencytype === 3) {
    item.state = 7;
    return 7
  }
  //不可合成，没有
  else {
    item.sortScore += 1000;
    item.state = 5;
    return 5;
  }
}

function getHeadState(item: HeadShopData) {
  if (model.user.activeRole === item.id) {
    return 2;
  }
  //已有，未使用
  else if (model.user.getItemNum(item.id) > 0) {
    return 1
  }
  //没有
  else if (item.purch === 1) {
    return 3
  } else {
    return 4
  }
}

class BtnSprite {
  btn: cc.Node

  constructor(btn: cc.Node, callback?: Function) {
    const scaleMin = cc.scaleTo(0.1, 0.8, 0.8)
    const scaleMax = cc.scaleTo(0.1, 1, 1)
    const action = cc.sequence(scaleMin, scaleMax, cc.callFunc(callback))

    this.btn = btn;
    btn.on(cc.Node.EventType.TOUCH_START, () => {
      btn.runAction(action);
      // if (callback) {
      // callback();
      // }
    })
  }
}

/*
弹出框动画，TODO：抽成DialogBase组件
*/

function dialogPopup(dialog: cc.Node, root: cc.Node) {
  root.scale = 0.9;
  root.stopAllActions();
  root.runAction(cc.sequence(
    cc.scaleTo(0.1, 1.1),
    cc.scaleTo(0.1, 1.0),
  ));
}

function dialogClose(dialog: cc.Node, root: cc.Node) {
  root.stopAllActions();
  root.runAction(cc.sequence(
    cc.scaleTo(0.1, 1.1),
    cc.scaleTo(0.1, 0.8),
    cc.callFunc(dialog.destroy, dialog)
  ));
}

function setIcon(iconSprite: cc.Sprite, iconId: string | number, itemType: string | number) {
  cc.loader.loadRes(`icon/${iconId}`, (err, res) => {
    iconSprite.spriteFrame = new cc.SpriteFrame(res);
    iconSprite.node.active = true;
  });
  if (itemType === ResType.skinPiece) {
    addPiece(iconSprite)
  }
}

async function addPiece(iconSprite: cc.Sprite) {
  return new Promise((resolve, reject) => {
    cc.loader.loadRes(`icon/piece`, cc.SpriteFrame, function (err, frame) {
      let piece = new cc.Node('piece');
      piece.parent = iconSprite.node;
      piece.addComponent(cc.Sprite).spriteFrame = frame;
      piece.x = (iconSprite.node.width - piece.width) / 2;
      piece.y = (iconSprite.node.height - piece.height) / 2;
      resolve(piece)
    });
  })
}

function getGameCount() {
  const b = cc.sys.localStorage.getItem('gameCount')
  if (b == null || b == '') {
    return 0
  }
  return parseInt(b)
}

function addGameCount() {
  const count = getGameCount()
  cc.sys.localStorage.setItem('gameCount', count + 1 + '')
}

function parseQuery(query: string) {
  // appid=2022090955&channel=10000&uid=1839698333&openid=oxbtr5fZbXnpyRreoMH5GHw5Kp70&time=1535534793&sign=964132a860c65268a819b5f29fe130b2
  const result = {}
  query.split('&').map(value => {
    return value.split('=')
  }).forEach(value => {
    result[value[0]] = value[1]
  })
  return result
}

export const utils = {
  randomName,
  btnify,
  getAward,
  formatToQuery,
  getSwimState,
  getHeadState,
  dialogPopup,
  dialogClose,
  setIcon,
  getGameCount,
  addGameCount,
  addPiece,
  parseQuery,
}